var createError = require('http-errors');
var express = require('express');
var path = require('path');
var ejs = require('ejs');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
app.listen(8080,function(){
  console.log("服务已开启")
})
// view engine setup
app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'jade');
app.engine('html',ejs.__express);
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({extended: true}))
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', require('./routes/index'));
app.use('/api', require('./routes/api'));
app.use('/admin', require('./routes/admin'));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

app.all('/*',function (req, res, next) { // 解决跨越问题
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  if (req.method == 'OPTIONS') {
    res.sendStatus(200);
  }
  else {
    next();
  }
});


const schedule = require('node-schedule');
const axios = require("axios");
function token() {
  let grant_type="client_credential"
  let appid="wx161d42f21bde379a"
  let secret ="35c576d99644f8a0d7568fea290178c3"
  let url ="https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+appid+"&secret="+secret
  axios.get(url)
      .then(result => {
        // handle success
        global.token=result.data.access_token
        console.log(new Date().toLocaleString(),",global token=",global.token);
      })
      .catch(error => {
        // handle error
        console.log(error);
      });
}
global.token=token()
const  scheduleCronstyle = ()=>{
  //每分钟的第30秒定时执行一次:
  schedule.scheduleJob('30 1 * * * *',()=>{
    token()
  });
}
scheduleCronstyle();



module.exports = app;
